#include "QStandardTreeNode.h"

QStandardTreeNode::QStandardTreeNode(const QList<QVariant>& data, QAbstractTreeNode* parent)
    : QAbstractTreeNode(parent)
{
    m_data = data;
    for(int i = 0; i < m_data.count(); i++) {
        m_userData.append(QVariant());
    }
    m_flags = (Qt::ItemIsSelectable | Qt::ItemIsEnabled);
}

QStandardTreeNode::QStandardTreeNode(const QString &data, QAbstractTreeNode *parent)
    : QAbstractTreeNode(parent)
{
    m_data << data;
    for(int i = 0; i < m_data.count(); i++) {
        m_userData.append(QVariant());
    }
    m_flags = (Qt::ItemIsSelectable | Qt::ItemIsEnabled);
}

QStandardTreeNode::~QStandardTreeNode()
{
}

int QStandardTreeNode::columnCount() const
{
    return m_data.count();
}

QVariant QStandardTreeNode::data(int column, int role) const
{
    if(role == Qt::DisplayRole) {
        if(column < 0 || column >= m_data.count())
            return QVariant(); //return invalid variant
        return m_data.at(column);
    }
    // On n'affiche l'icon que pour la premiere colonne
    else if(column == 0 && role == Qt::DecorationRole) {
        return icon;
    }
    else if(role == Qt::UserRole) {
        if(column < 0 || column >= m_userData.count()) return QVariant();
        return m_userData.at(column);
    }
    return QVariant();
}

bool QStandardTreeNode::setData(QVariant data, int column, int role)
{
    if(role == Qt::DisplayRole) {
        if(column < 0 || column >= m_data.count())
            return false;
        m_data[column] = data;
        return true;
    }
    else if(role == Qt::DecorationRole) {
        if(column != 0) {
            return false;
        }
        icon = data.value<QIcon>();
        return true;
    }
    else if(role == Qt::UserRole) {
        if(column < 0 || column >= m_userData.count()) {
            return false;
        }
        m_userData[column] = data;
        return true;
    }
    return false;
}

bool QStandardTreeNode::insertColumns(int position, int count)
{
    if (position < 0 || position > m_data.size())
        return false;
    for (int column = 0; column < count; ++column) {
        m_data.insert(position, QVariant());
        m_userData.insert(position, QVariant());
    }
    foreach (QAbstractTreeNode *child, m_children)
        child->insertColumns(position, count);
    return true;
}

bool QStandardTreeNode::removeColumns(int position, int count)
{
    if (position < 0 || position+count > m_data.count())
        return false;
    for (int column = 0; column < count; ++column) {
        m_data.removeAt(position);
        m_userData.removeAt(position);
    }
    foreach (QAbstractTreeNode *child, m_children)
        child->removeColumns(position, count);
    return true;
}

Qt::ItemFlags QStandardTreeNode::flags() const
{
    return m_flags;
}

void QStandardTreeNode::setFlags(Qt::ItemFlags flags)
{
    m_flags = flags;
}
